﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using CatchUpTv.Tv;
using log4net;
using System.Xml.Linq;
using CatchUpTv.Utilities;
using System.Text.RegularExpressions;
using System.Web;

namespace CatchUpTv.Downloader.Australia.Sbs
{
    /// <summary>
    /// A category in SBS catch up TV.
    /// </summary>
    public class Category
    {
        /// <summary>
        /// The logger for this class.
        /// </summary>
        static ILog log = LogManager.GetLogger(typeof(Category));

        /// <summary>
        /// The URL.
        /// </summary>
        string _url;

        public Category(string url)
        {
            _url = url;
        }

        /// <summary>
        /// Gets the list of shows under this category.
        /// </summary>
        /// <returns>The list of shows.</returns>
        public IEnumerable<Show> GetShows()
        {
            WebClient webClient = new WebClient();

            // Get the show list
            var rawXml = webClient.DownloadString(_url);

            if (log.IsDebugEnabled)
            {
                log.DebugFormat("XML: '{0}'", rawXml);
            }

            XDocument xml = XDocument.Parse(rawXml);
            var videoElements = xml.Descendants("video");


            HashSet<Show> shows = new HashSet<Show>();

            foreach (var video in videoElements)
            {
                string episodeId = video.Attribute("id").Value;
                string episodeName = video.Attribute("name").Value;
                string episodeSource = video.Attribute("src").Value;

                string episodeTitle = video.Element("title").Value;
                string episodeDescription = video.Element("description").Value;                
                int duration = Int32.Parse(video.Element("duration").Value);
                string imageUrl = video.Element("media").Element("image").Attribute("src").Value;
                
                string showName = video.Element("primarygroup").Value == "Documentary"
                    ? "Documentary"
                    : EpisodeRegex.Replace(episodeTitle, "").Trim();

                string showId = "SBS_AU_Show_" + showName.Replace(" ", "_").Replace("'", "");

                Show show;
                SbsShow sbsShow;

                if (shows.Count(s => s.Id == showId) > 0)
                {
                    show = shows.First(s => s.Id == showId);
                    sbsShow = show.Tag as SbsShow;
                }
                else
                {
                    sbsShow = new SbsShow();

                    show = new Show()
                    {
                        Id = showId,
                        Name = showName,
                        Tag = sbsShow,
                        ImageUrl = imageUrl,
                        Episodes = new Lazy<IEnumerable<Episode>>(sbsShow.GetEpisodes)
                    };

                    shows.Add(show);
                }

                sbsShow.Episodes.Add(new Episode()
                {
                    Id = "SBS_AU_episode_" + episodeId,
                    Tag = episodeSource,
                    Name = episodeTitle,
                    Duration = TimeSpan.FromSeconds(duration),
                    Description = episodeDescription,
                    ImageUrl = imageUrl
                });
            }

            return shows;
        }

        private static readonly Regex EpisodeRegex = new Regex("Ep \\d*.*");
    }

    public class SbsShow
    {
        public IList<Episode> Episodes { get; private set; }

        public SbsShow()
        {
            Episodes = new List<Episode>();
        }

        /// <summary>
        /// Get the list of episodes for this show.
        /// </summary>
        /// <returns>The list of episodes</returns>
        public IEnumerable<Episode> GetEpisodes()
        {
            return Episodes;
        }
    }
}
